<template>
  <div class="assignment-area">
    <h2 class="title">作业栏</h2>
    <div class="workarea">
      <div class="left-part">
        <div class="assignment-form">
          <h2>作业上传</h2>

          <form @submit.prevent="submitAssignment">
            <div class="form-group">
              <label for="assignmentName">作业名称：</label>
              <input type="text" v-model="assignment.title" id="assignmentName" placeholder="输入作业名称" />
            </div>

            <div class="form-group">
              <label for="assignmentContent">作业内容：</label>
              <textarea v-model="assignment.text" id="assignmentContent" placeholder="输入作业内容"></textarea>
            </div>

            <div class="form-group">
              <label for="dueDate">截止时间：</label>
              <input 
                type="text" 
                v-model="assignment.deadLine" 
                id="dueDate" 
                placeholder="请输入截止时间（格式：yyyy-MM-dd HH:mm:ss）"
                style="width: 100%;" 
              />
            </div>

            <div class="form-group">
              <label for="assignmentFile">上传文件：</label>
              <input type="file" @change="handleFileUpload" id="assignmentFile" />
            </div>

            <button type="submit">发布作业</button>
          </form>
        </div>
      </div>

      <div class="right-part">
        <div class="assignment-table">
          <el-table :data="tableData" stripe>
            <el-table-column label="作业Id" prop="id" />
            <el-table-column label="作业名称" prop="name" />
            <el-table-column label="截止日期" prop="deadline" />
            <el-table-column label="操作">
              <template #default="scope">
                <el-button type="primary" @click="goToHomeworkDetail(scope.row.id)">管理</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

axios.defaults.baseURL = "http://localhost:8085";

export default {
  data() {
    return {
      assignment: {
        courseId: this.$route.params.courseId,
        title: '',
        text: '',
        deadLine: '',
        file: null,
      },
      tableData: [],
    };
  },
  mounted() {
    this.fetchHomeworkData();
  },
  methods: {
    goToHomeworkDetail(homeworkId) {
      this.$router.push({ name: 'HomeworkDetail', params: { homeworkId } });
    },
    async fetchHomeworkData() {
      try {
        const courseId = parseInt(this.assignment.courseId);
        const response = await axios.get('/homework/viewhomeworkitem', {
          params: { courseId }
        });

        this.tableData = response.data.map(item => ({
          id: item.homeworkId,   // 使用返回数据中的作业ID
          name: item.title,      // 使用返回数据中的作业名称
          deadline: item.deadLine // 使用返回数据中的截止日期
        }));
      } catch (error) {
        this.$message.error('获取作业数据失败: ' + error.message);
      }
    },
    handleFileUpload(event) {
      this.assignment.file = event.target.files[0];
    },
    async submitAssignment() {
      try {
        const formData = new FormData();
        formData.append('file', this.assignment.file);
        formData.append('title', this.assignment.title);
        formData.append('text', this.assignment.text);
        formData.append('courseId', parseInt(this.assignment.courseId));
        formData.append('deadLine', this.assignment.deadLine);

        const response = await axios.post('/homework/publishhomework', formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
          },
        });

        if (response.status === 200) {
          this.$message.success('作业上传成功！');
          this.fetchHomeworkData(); // 更新作业列表
        } else {
          this.$message.error('作业上传失败，请稍后再试。');
        }
      } catch (error) {
        this.$message.error('上传出错: ' + error.message);
      }
    },
  },
};
</script>

<style scoped>
.assignment-area {
  width: 90%;
  margin: 0 auto;
  text-align: center;
}
.workarea {
  display: flex;
}
.left-part {
  width: 30%;
}
.right-part {
  width: 70%;
  padding: 50px;
}

.title {
  font-size: 50px;
  font-weight: bold;
  margin-bottom: 20px;
}

.assignment-form {
  max-width: 400px;
  margin-left: auto;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 8px;
  background-color: #f9f9f9;
}

.form-group {
  margin-bottom: 15px;
}

label {
  display: block;
  font-weight: bold;
  margin-bottom: 5px;
}

input[type='text'],
input[type='file'],
textarea {
  width: 90%;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

button {
  display: inline-block;
  padding: 10px 20px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:hover {
  background-color: #45a049;
}

.assignment-table {
  width: 100%;
  border-collapse: collapse;
  margin-right: auto;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 8px;
  background-color: #f9f9f9;
}
</style>
